import { reactive } from "vue"
import type { JSX } from "vue/jsx-runtime"
import { Option, Radio, Checkbox } from 'view-ui-plus'
import request from '@/axios'
import { getFuncFromString, toCamelCase } from "./useUtil"

interface dataSource {
  type: string
  value: any,
  url: string,
  resultFn: string
}

const keyField = 'option_key'
const displayField = 'option_desc'
async function initDataSourceList(dataSource: dataSource, pmInstance: any): Promise<any[]> {
  const { type, value, url, resultFn } = dataSource
  let result: any[] = []
  switch (type) {
    case 'static':
      if (typeof value === 'string') {
        try {
          result = JSON.parse(value)
        } catch (error) {
          
        }
      } else {
        result = value
      }
      break
    case 'fetch':
      if (url && resultFn && resultFn.includes('function')) {
        try {
          const { data } = await request({
            url,
            method: 'post'
          })
          const exposed = pmInstance ? (pmInstance as any).exposed : null
          result = getFuncFromString(resultFn).call(null, exposed, data) || []
        } catch (error) {
          
        }
      }
      break
  }
  return result
}
export default async function useOptionsVNode(dataSource: dataSource, component: string, pmInstance: any): Promise<JSX.Element[] | null> {
  if (dataSource) {
    const optionList = reactive(await initDataSourceList(dataSource, pmInstance))
    if (optionList) {
      switch (toCamelCase(component)) {
        case 'eSelect':
          return (
            optionList.map(item => (
              <Option key={item[keyField]} value={item[keyField]}>{ item[displayField] }</Option>
            ))
          )
        case 'eRadioGroup':
          return (
            optionList.map(item => (
              <Radio key={item[keyField]} label={item[keyField]}>{ item[displayField] }</Radio>
            ))
          )
        case 'eCheckboxGroup':
          return (
            optionList.map(item => (
              <Checkbox key={item[keyField]} label={item[keyField]}>{ item[displayField] }</Checkbox>
            ))
          )
      }
    }
  }
  return null
}